package com.shao.serialize;

import com.shao.serialize.impl.HessianSerialize;
import com.shao.serialize.impl.JdkSerialize;
import com.shao.serialize.impl.JsonSerialize;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author PaoFu
 * @version 1.0
 * @data 2025/4/28 14:41
 */
public class SerializerFactory {

    private static final ConcurrentHashMap<String, SerializerWrapper> SERIALIZER_CACHE = new ConcurrentHashMap<>(8);
    private static final ConcurrentHashMap<Byte, SerializerWrapper> SERIALIZER_TYPE = new ConcurrentHashMap<>(8);

    static {
        SerializerWrapper jdk = new SerializerWrapper((byte) 1, "jdk", new JdkSerialize());
        SerializerWrapper json = new SerializerWrapper((byte) 2, "json", new JsonSerialize());
        SerializerWrapper hessian = new SerializerWrapper((byte) 3, "hessian", new HessianSerialize());
        SERIALIZER_CACHE.put("jdk", jdk);
        SERIALIZER_CACHE.put("json", json);
        SERIALIZER_CACHE.put("hessian", hessian);

        SERIALIZER_TYPE.put((byte) 1, jdk);
        SERIALIZER_TYPE.put((byte) 2, json);
        SERIALIZER_TYPE.put((byte) 3, hessian);
    }

    /**
     * 使用工厂方法获取SerializerWrapper
     * @param serializeType 序列化类型
     * @return 返回SerializerWrapper
     */
    public static SerializerWrapper getSerializer(String serializeType) {
        return SERIALIZER_CACHE.get(serializeType.toLowerCase()) != null
                ? SERIALIZER_CACHE.get(serializeType.toLowerCase())
                : SERIALIZER_CACHE.get("jdk");
    }

    /**
     * 使用工厂方法获取SerializerWrapper
     * @param serializeCode 序列化状态码
     * @return 返回SerializerWrapper
     */
    public static SerializerWrapper getSerializer(byte serializeCode) {
        return SERIALIZER_TYPE.get(serializeCode) != null
                ? SERIALIZER_TYPE.get(serializeCode)
                : SERIALIZER_TYPE.get((byte) 1);
    }
}
